import { Injectable } from '@angular/core';
import { SQLiteObject, SQLite } from '@ionic-native/sqlite';
import { Platform } from 'ionic-angular/platform/platform';

@Injectable()
export class SqliteHelperProvider {

  //sqlite_native不支持Browser
  //在Browser端使用WebSQL(w3c废弃)
  database: SQLiteObject;
  win_db: any;//h5数据库
  win: any = window;//window对象

  constructor(private platform: Platform,
    private sqlite: SQLite
    ) {
    
  }

  /**
   * 创建或打开数据库
   */
  createOrOpenDb() : Promise<any>{
    return new Promise<any>((resolve, reject)=>{
      if(this.isMobile()){
        this.sqlite.create({name: 'park_data_3.db',location: 'default'}).then((db: SQLiteObject) => {
          this.database = db;
          //创建数据表的sql语句
          this.createTable().then(res=>resolve(res), err=>reject(err));
        })
        .catch(e => {
          console.error(e);
          reject(e);
        });
      }else{
        this.win_db = this.win.openDatabase('park_data_4.db', '1.0', '景区信息表', 60 * 1024 * 1024);
        //创建数据表的sql语句
        this.createTable().then(res=>resolve(res), err=>reject(err));
      }
    });
  }

  /**
   * 创建数据表
   */
  createTable(): Promise<any>{
    let sql: string = 'CREATE TABLE IF NOT EXISTS parks_lite(objectId TEXT, name TEXT, point TEXT )';
    return this.executeSql(sql, []);
  }

  /**
   * 执行sql语句
   * @param sql 
   * @param array 
   */
  executeSql(sql: string, params: Array<any>): Promise<any>{
      if(this.isMobile()){
        if(this.database){
          return this.execLocalSql(sql, params);
        }
      }else{
        if(this.win_db){
          return this.execWebSql(sql, params);
        }
      }
      return new Promise(resolve=>resolve([]));
  }

  /**
   * 执行基于本地SQLite的sql语句
   * @param sql 
   * @param params
   */
  private execLocalSql(sql: string, params : Array<any>):Promise<any>{
    return this.database.executeSql(sql, params);
  }
  /**
   * 执行基于WEB SQL的SQL语句
   * @param sql 
   * @param params 
   */
  private execWebSql(sql: string, params: Array<any>):Promise<any>{
    return new Promise((resolve, reject)=>{
        this.win_db.transaction((tx)=>{
          tx.executeSql(sql, params, (tx, res)=>resolve(res), (tx,err)=>reject(err));
        },(err)=> reject(err));
    });
  }

  /**
   * 判断是否为真机环境
   */
  isMobile(): boolean{
    return this.platform.is('mobile') && !this.platform.is('mobileweb');
  }

}
